import React from 'react';
import fetch from 'isomorphic-fetch';
import findIndex from 'lodash/findIndex';
import Toast from 'antd-mobile/lib/toast';
import Modal from 'antd-mobile/lib/modal';
import BackNav from 'shared/components/BackNav';
import {
  buyProductApi,
  fetchAddresslistApi,
  alipayApi,
  wxpayApi,
  checkPaymentStatusApi,
  expressChargeApi
} from 'shared/api';
import { wxpayh5Pay } from 'shared/commonFetch';
import localstorage from 'shared/utils/localStorage';
import {
  checkoutConfirmApi,
  buyCartListApi,
  checkoutCartConfirmApi,
  fetchGroupBuyListApi,
  checkoutGroupbuyConfirmApi
} from './api';
import ReceiverAddress from './ReceiverAddress';
import ProductOrderList from './ProductOrderList';
import PaymentInfo from './PaymentInfo';
import './index.less';

const paymentBorder = require('static/payment-border.png');

const { alert } = Modal;
export default class OrderDetails extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      data: {
        productlist: []
      },
      addresslistData: [],
      defaultAddressIndex: -1,
      timeCount: 90,
      charge: 0
    }

    this.productList = []
  }

  componentDidMount() {
    fetchAddresslistApi().then(({ code, data }) => {
      if (code === 1000) {
        const defaultAddressIndex = findIndex(data, (item) => item.default === 1)
        this.setState({ addresslistData: data, defaultAddressIndex })

        if (data.length) {
          if (defaultAddressIndex !== -1) {
            this.defaultAddressData = data[defaultAddressIndex];
          } else {
            this.defaultAddressData = data[0];
          }

          this.address_id = this.defaultAddressData.address_id
        }
      }
    })

    this.fetchProductData()

    // Toast.info(localstorage.get('wxCode'));
  }

  componentWillUnmount() {
    window.clearTimeout(this.checkPaymentCount);
    window.clearInterval(this.timeOver);
  }

  fetchProductData = () => {
    const { type } = this.props.match.params;
    if (type === 'buyCart') {
      buyCartListApi().then(({ data }) => {
        if (data) {
          this.setState({ data });
          const { productlist } = data;
          this.productinfo = ''
          productlist.forEach(({ product_id, quantity }) => {
            this.productinfo += `${product_id}-${quantity},`
            this.productList.push({ product_id, quantity })
          })
          this.productinfo = this.productinfo.slice(0, -1)
          if (this.defaultAddressData) {
            this.expressCharge(this.defaultAddressData.province_id, this.productList)
          }
        }
      })
    } else if(type === 'groupBuyProduct') {
      fetchGroupBuyListApi({
        product_id: localstorage.get('product_id'),
        sub_product_ids: localstorage.get('sub_product_ids')
      }).then(({ data }) => {
        if (data) {
          this.setState({ data });
          const { productlist } = data;
          this.productList = productlist.map(({ product_id, quantity }) => ({ product_id, quantity }))
          if (this.defaultAddressData) {
            this.expressCharge(this.defaultAddressData.province_id, this.productList)
          }
        }
      })
    } else {
      this.productinfo = localstorage.get('productinfo');
      buyProductApi({ productinfo: this.productinfo }).then(({ data }) => {
        if(data) {
          this.setState({ data });
          const { productlist } = data;
          this.productList = productlist.map(({ product_id, quantity }) => ({ product_id, quantity }))
          if (this.defaultAddressData) {
            this.expressCharge(this.defaultAddressData.province_id, this.productList)
          }
        }
      })
    }
  }

  expressCharge(province_id, productlist) {
    expressChargeApi({ productlist, province_id }).then((res) => {
      if (res.code === 1000) {
        this.setState({ charge: res.data.charge })
      }
    })
  }

  onSetAddress = (data) => {
    this.expressCharge(data.province_id, this.productList)
    this.address_id =data.address_id;
  }

  onSelectPayment = (value) => {
    this.payment_method = value;
  }

  checkPaymentStatus(orderId) {
    checkPaymentStatusApi(orderId).then((res) => {
      if (res.code === 1000 && res.data.ispaid) {
        window.clearTimeout(this.checkPaymentCount);
        __self.history.push('/PaymentSuccess')
      }
    })
  }

  onHandleCoupon = ({ coupon_id }, data) => {
    this.coupon_id = coupon_id;
    if (data) {
      this.setState({ data: {...data} });
    }
  }

  checkoutProductQuantity = () => {
    const { data: { productlist } } = this.state;
    let quantitySufficient = false;
    for (let i = 0; i < productlist.length; i++){
      let item = productlist[i];
      if (item.selected && (item.quantity > item.totalquantity)) {
        Toast.fail(`${item.title} 库存数量不足`)
        quantitySufficient = true;
        break;
      }
    }

    if (quantitySufficient) {
      return true;
    }

    return false;
  }

  renderNormalInvoice = (lastinvoice) => {
    return (
      <div className="alert-invoice">
        <p>发票抬头类型：<span>{lastinvoice.title  ||'个人' }</span></p>
        <p>企业识别号：<span>{lastinvoice.idcode}</span></p>
        <p>发票内容：商品明细</p>
        <p>收票人手机号：<span>{lastinvoice.receiver_mobile}</span></p>
        <p>收票人邮箱：<span>{lastinvoice.receiver_email}</span></p>
      </div>
    )
  }

  renderSpecialInvoice = (lastinvoice) => {
    return (
      <div className="alert-invoice">
        <p>单位名称：<span>{lastinvoice.title}</span></p>
        <p>企业识别号：<span>{lastinvoice.idcode}</span></p>
        <p>注册地址:<span>{lastinvoice.register_address}</span></p>
        <p>注册电话:<span>{lastinvoice.register_phone}</span></p>
        <p>开户银行：<span>{lastinvoice.register_bank}</span></p>
        <p>银行账户：<span>{lastinvoice.register_bank_num}</span></p>
        <p>收票人姓名：<span>{lastinvoice.receiver_fullname}</span></p>
        <p>收票人手机：<span>{lastinvoice.receiver_mobile}</span></p>
        <p>邮政编码：<span>{lastinvoice.receiver_postCode}</span></p>
        <p>收票人省份：<span>{`${lastinvoice.receiver_province}${lastinvoice.receiver_city}${lastinvoice.receiver_county}`}</span></p>
        <p>详细地址：<span>{lastinvoice.receiver_address}</span></p>
      </div>
    )
  }

  onSubmit = () => {
    if (this.checkoutProductQuantity()) {
      return false;
    }


    if (!this.address_id) {
      Toast.fail('请选择地址', 1);
      return false
    }

    if (!this.payment_method) {
      Toast.fail('请选择支付方式', 1);
      return false
    }

    const { data: { lastinvoice = {} } } = this.state;
    const isSpecialInvoice = +lastinvoice.invoice_type === 2;
    const content = isSpecialInvoice ?
      this.renderSpecialInvoice(lastinvoice)
      :
      this.renderNormalInvoice(lastinvoice)

    alert(isSpecialInvoice ? '增值税专用发票' : '电子普通发票', content, [
      { text: '取消', onPress: () => console.log('cancel'), style: 'default' },
      { text: '确定', onPress: () => this.checkout() },
    ]);
  }

  checkout = () => {
    const proData = {
      productinfo: this.productinfo,
      address_id: this.address_id,
      payment_method: this.payment_method,
    }
    const { data } = this.state;

    if (data.lastinvoice.invoice_id) {
      proData.invoice_id = data.lastinvoice.invoice_id;
    }

    if (this.coupon_id) {
      proData.coupon_id = this.coupon_id
    }

    const { type } = this.props.match.params;
    let checkoutConfirm = checkoutConfirmApi;
    if (type === 'buyCart') {
      checkoutConfirm = checkoutCartConfirmApi;
    } else if (type === 'groupBuyProduct') {
      checkoutConfirm = checkoutGroupbuyConfirmApi
      proData.sub_product_ids = localstorage.get('sub_product_ids');
      proData.product_id = localstorage.get('product_id');
      delete proData.productinfo
    }

    Toast.loading('加载中', 10)

    checkoutConfirm(proData).then((res) => {
      Toast.hide();
      if (res.code === 1000) {
        const { data } = res
        const orderId = { order_id: data.order_id, wxpayh5: 1 }
        if (this.payment_method === 'weixin') {
          const wxCode = localstorage.get('wxCode');
          // alert(wxCode)
          // 微信公众号支付
          if (wxCode) {
            wxpayh5Pay({ order_id: data.order_id, code: wxCode })
            return;
          }
          // let a = 90;
          wxpayApi(orderId).then((res) => {
            if (res.code === 1000) {
              localstorage.setObject('payRes', {
                order_id: data.order_no
              })

              this.setState({ wxUrl: res.data.wxpayh5url }, () => {
                document.querySelector("#open-wx").click()
              })
            } else {
              Toast.fail('服务端错误', 1);
            }
          })
        } else {
          let userInfo = window.localStorage.getItem('userInfo');
          if (userInfo) {
            userInfo = JSON.parse(userInfo)
          }

          const alipayData = { orderId: data.order_id, ...userInfo };

          fetch(alipayApi(alipayData))
            .then(function (response) {
              return response.text()
            }).then(function (res) {
              const div = document.createElement('div') // 创建div
              div.innerHTML = res // 将返回的form 放入div
              div.style.opacity = 0
              document.body.appendChild(div)
              document.forms[0].submit()
            })
        }
      } else if (res.code === 1006) {
        Toast.fail(res.info, 1)
      }
    })
  }

  onClose = () => {
    this.setState({ showWxpay: false });
    window.clearInterval(this.timeOver);
  }

  render() {
    const { data, addresslistData, defaultAddressIndex, wxpayImg, timeCount, charge, wxUrl } = this.state;
    return (
      [
        <BackNav key='back-nav' title="确认订单" />,
        <div className="order" key="order">
          <a href={wxUrl} id="open-wx" style={{ display: 'none' }} >openWx</a>
          <ReceiverAddress addresslist={addresslistData} setAddress={this.onSetAddress} defaultAddressIndex={defaultAddressIndex} />
          <img src={paymentBorder} alt="" className="order-header-border" />
          {
            data.productlist && data.productlist.map((item, index)=>(<ProductOrderList key={index} item={item} />))
          }

          <PaymentInfo
            data={data}
            onSubmit={this.onSubmit}
            onSelectPayment={this.onSelectPayment}
            onHandleCoupon={this.onHandleCoupon}
            fetchProductData={this.fetchProductData}
            charge={charge}
          />

          {/* <Modal
            visible={this.state.showWxpay}
            transparent
            maskClosabl
            footer={[{
              text: '关闭支付', onPress: () => {
                window.clearInterval(this.timeOver);
                window.clearTimeout(this.checkPaymentCount);
                this.onClose();
                __self.history.push('/account/order')
              }
            }]}
            onClose={this.onClose}
            title="微信支付"
          >
            <div>
              <p>请在{timeCount}内支付</p>
              <img src={wxpayImg} alt="" />
            </div>
          </Modal> */}
        </div>
      ]
    )
  }
}